from pyb import UART

_wind_cmd = b'\x01\x03\x00\x0A\x00\x02\xE4\x09'
_crc_table = [0x0000, 0xA001]

class WIND:
	def __init__(self):
		self._uart = UART(1)
		self._uart.init(9600)
		self._dir = 0
		self._speed = 0

	def readReq(self):
		num = self._uart.any()
		if (num):
			self._uart.read(num)

		self._uart.write(_wind_cmd)

	def _crc(self, data):
		_c = 0xFFFF
		_xor = 0
		for i in range(len(data)):
			_c ^= data[i]
			for bit in range(8):
				_xor = _c & 0x01
				_c >>= 1
				_c ^= _crc_table[_xor]

		return _c

	def readData(self):
		data = self._uart.read(9)

		if ((data != None) and (len(data) >= 9)):
			_c = self._crc(data[:-2])
			if (_c == (data[7] + (data[8] << 8))):
				self._speed = (data[3] << 8) + data[4]
				self._dir = (data[5] << 8) + data[6]
			else:
				print("data:", hex(data[8]), hex(data[7]))
				print('crc:', hex(_c))

		return self._dir, self._speed

